import Vue from 'vue'
import Vuex from 'vuex'
import router from '../router/index'
import axios from 'axios'
import { Message } from 'element-ui'
Vue.use(Vuex)

export default new Vuex.Store({
  actions: { /* 组件的行为和方法, 可以包含任意异步操作 */
    changNameAction (context, str) {
      console.log(context, str)
      context.commit('changeNameMutate', str)
    },
    /* 登录的方法 */
    loginInAction ({ commit }, route) {
      commit('loginInMutate')
      router.push({ path: '/home' })
    },
    /* 请求所有需要显示的学生数据 */
    getAllDataAction ({ commit }) {
      axios({
        method: 'get',
        url: '/mock/42/stuDate'
      }).then(res => {
        console.log(res)
        console.log(res.data.code)
        if (res.data.code === 400) {
          // 模拟请求失败
          Message({
            message: '模拟后端请求失败',
            type: 'error'
          }) // 消息提示
        } else if (res.data.code === 200) {
          // 将数据写到 vuex 当中
          console.log(res.data.data, '')
          commit('getAllDataMutate', res.data.data)
        }
      }).catch(err => {
        console.log(err, '')
      })
    },
    /* 设置显示页数 */
    setShowpageAction ({ commit }, num) {
      commit('setShowpageMutate', num)
    },
    /* 删除棕的数组里面的数据 */
    deleteFromAllDataAction (context, index) {
      console.log(context)
      // commit('deleteFromAllDataMutate', id)
      const indexInAllData = (context.state.showpage - 1) * 5 + index
      context.commit('deleteFromAllDataMutate', indexInAllData)
    }
  },
  mutations: { /* 改变状态的, 必须同步执行 */
    changeNameMutate (state, str) {
      state.name = str
    },
    loginInMutate (state) {
      state.isLogin = true
    },
    getAllDataMutate (state, obj) {
      state.allData = obj
    },
    setShowpageMutate (state, num) {
      state.showpage = num
    },
    deleteFromAllDataMutate (state, index) {
      // state.allData.filter(item => !(item.id === id))
      state.allData.splice(index, 1)
    }
  },
  state: { /* 状态,组件根据状态渲染页面 */
    name: 'vuex里面管理的name',
    isLogin: false,
    allData: [],
    showpage: 1
  },
  getters: { /* 获取状态的 */
    getNameGetter (state) {
      return state.name + 'GETTER'
    },
    /* 获取学生数据的总数 */
    getTotal (state) {
      return state.allData.length
    },
    getShowData (state) {
      const start = (state.showpage - 1) * 5
      const end = state.showpage * 5
      return state.allData.slice(start, end)
    }
  },
  modules: {
  }
})
